package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @program: day0808
 * @author: 枉度生
 * @description:
 * @create: 2025-08-08 14:31
 */
@Component
public class GatewayFilter implements GlobalFilter {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest req = exchange.getRequest();

        ServerHttpResponse resp = exchange.getResponse();

        String url = req.getPath().toString();

        if (url.contains("/user/login")){
            System.out.println("登录方法无须拦截");
            return chain.filter(exchange);
        }
        if (url.contains("/user/sendCode/")){
            System.out.println("发送验证码无须拦截");
            return chain.filter(exchange);
        }
        if (url.contains("/user/register")){
            System.out.println("注册无须拦截");
            return chain.filter(exchange);
        }
        if (url.contains("/user/forgot")){
            System.out.println("忘记密码无须拦截");
            return chain.filter(exchange);
        }

        String token = req.getHeaders().getFirst("token");
        if (token==null){
            System.out.println("本地token不存在");
            resp.setStatusCode(HttpStatus.UNAUTHORIZED);
            return resp.setComplete();
        }

        Claims claims = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = claims.get("userId", Integer.class);
        String key="token"+userId;

        String redisToken = stringRedisTemplate.opsForValue().get(key);
        if (redisToken==null){
            System.out.println("redis 中 token 不存在");
            resp.setStatusCode(HttpStatus.UNAUTHORIZED);
            return resp.setComplete();
        }

        if (!redisToken.equals(token)){
            System.out.println("异域登录");
            resp.setStatusCode(HttpStatus.UNAUTHORIZED);
            return resp.setComplete();
        }

        Long expire = stringRedisTemplate.getExpire(key);
        if (expire<=600){
            stringRedisTemplate.expire(key, 30, TimeUnit.MINUTES);
        }

        System.out.println("token 验证通过");

        return chain.filter(exchange);
    }
}
